﻿using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Threading;
using System.Web.Mvc;
using KPIS.GERP.Models;
using KPIS.GERP.Models.SYS.ViewModel;
using WebMatrix.WebData;

namespace KPIS.GERP.WEB.GIMS.Filters
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public sealed class InitializeSimpleMembershipAttribute : ActionFilterAttribute
    {
        private static SimpleMembershipInitializer _initializer;
        private static object _initializerLock = new object();
        private static bool _isInitialized;

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            // Ensure ASP.NET Simple Membership is initialized only once per app start
            LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
        }

        private class SimpleMembershipInitializer
        {
            public SimpleMembershipInitializer()
            {
                Database.SetInitializer<GERPContext>(null);

                try
                {
                    using (var context = new GERPContext())
                    {
                        if (!context.Database.Exists())
                        {
                            // Create the SimpleMembership database without Entity Framework migration schema
                            ((IObjectContextAdapter) context).ObjectContext.CreateDatabase();
                        }

                        WebSecurity.InitializeDatabaseConnection("GERPContext", "UserProfile", "UserId", "UserName", autoCreateTables: true);

                        var roles = (WebMatrix.WebData.SimpleRoleProvider)System.Web.Security.Roles.Provider;
                        var membership = (WebMatrix.WebData.SimpleMembershipProvider)System.Web.Security.Membership.Provider;
                        if (!roles.RoleExists("Admins"))
                        {
                            roles.CreateRole("Admins");
                        }
                        if (membership.GetUser("admin", false) == null)
                        {
                            membership.CreateUserAndAccount("admin", "1234");
                        }
                        var rs = roles.GetRolesForUser("admin");
                        bool containAdmin = rs.Any(r => r.ToLower().Equals("admins"));
                        if (containAdmin)
                        {
                            roles.AddUsersToRoles(new[] { "admin" }, new[] { "Admins" });
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
                }
            }
        }
    }
}